'use strict';

const fs = require('fs');
const path = require('path');
const userHome = require('os').homedir();

const log = require('@x3-cli-dev/log');
const { getLatestVersion } = require('@x3-cli-dev/npm');

const dotenv = require('dotenv');
const rootCheck = require('root-check');
const semver = require('semver');
const commander = require('commander');
const colors = require('colors');

const pkg = require('../package.json');
const { LOWEST_NODE_VERSION, X3_CLI_ENV_FILENAME, X3_DEFAULT_CLI_HOME, NPM_NAME } = require('./cont');
const { registerGlobal, registerInit, registerPublish, registerSvn, registerConfig, registerClean, registerInstall, registerProxy } = require('./register');

const program = new commander.Command();

async function cli(argv) {
  try {
    await prepare();
    registerCommand(argv);
  } catch (error) {
    log.error(error.message);
    if (program.opts().debug) {
      console.log(error);
    }
  }
}

function registerCommand(argv) {
  registerGlobal(program);
  registerInit(program);
  registerPublish(program);
  registerSvn(program);
  registerConfig(program);
  registerClean(program);
  registerInstall(program);
  registerProxy(program);

  program.parse(argv);

  if (program.args && program.args.length < 1) {
    program.outputHelp();
    console.log();
  }
}

async function prepare() {
  checkCliVersion();
  checkNodeVersion();
  checkRoot();
  checkUserHome();
  checkEnv();
  await checkCliUpdate();
}

function checkCliVersion() {
  log.notice(`cli`, pkg.version);
}

function checkNodeVersion() {
  if (semver.lt(process.version, LOWEST_NODE_VERSION)) {
    throw new Error(colors.red(`x3-cli-dev 需要安装 v${LOWEST_NODE_VERSION} 以上版本的 Node.js`));
  }
}

function checkRoot() {
  rootCheck();
}

function checkUserHome() {
  if (!userHome || !fs.existsSync(userHome)) {
    throw new Error(colors.red('当前登录用户主目录不存在！'));
  }
}

function checkEnv() {
  const envPath = path.resolve(userHome, X3_CLI_ENV_FILENAME);
  dotenv.config({
    path: envPath,
  });
  createDefaultCliConfig(); // 准备基础配置
}

function createDefaultCliConfig() {
  const cliConfig = {
    home: userHome,
  };
  if (process.env.X3_CLI_HOME) {
    cliConfig['cliHome'] = path.resolve(userHome, process.env.X3_CLI_HOME);
  } else {
    cliConfig['cliHome'] = path.resolve(userHome, X3_DEFAULT_CLI_HOME);
  }
  process.env.X3_CLI_HOME_PATH = cliConfig.cliHome;
}

async function checkCliUpdate() {
  const currentVersion = pkg.version;
  const lastVersion = await getLatestVersion(NPM_NAME);
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      colors.yellow(`请手动更新 ${NPM_NAME}，当前版本：${pkg.version}，最新版本：${lastVersion}
                更新命令： npm install -g ${NPM_NAME}`),
    );
  }
}

module.exports = cli;
